package com.wj.dubbo.service.welfareshop.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.wj.console.bean.welfareshop.param.CreateOrderParam;
import com.wj.console.bean.welfareshop.param.SalesReturnOrNifferApplyParam;
import com.wj.console.bean.welfareshop.result.Address;
import com.wj.console.bean.welfareshop.result.AfterSaleDetail;
import com.wj.console.bean.welfareshop.result.Cate;
import com.wj.console.bean.welfareshop.result.CommodityStatus;
import com.wj.console.bean.welfareshop.result.CreateOrderResult;
import com.wj.console.bean.welfareshop.result.Image;
import com.wj.console.bean.welfareshop.result.LogisticsMsg;
import com.wj.console.bean.welfareshop.result.OrderDetail;
import com.wj.console.bean.welfareshop.result.Price;
import com.wj.console.bean.welfareshop.result.ProductDetail;
import com.wj.console.bean.welfareshop.result.Remain;
import com.wj.console.bean.welfareshop.result.ResultMsg;
import com.wj.console.bean.welfareshop.result.SalesReturnMsg;
import com.wj.console.bean.welfareshop.result.SalesReturnOrNifferApplyResult;
import com.wj.console.bean.welfareshop.result.Stock;
import com.wj.console.common.exception.BusinessException;
import com.wj.console.constant.Enums.CACHE_KEY;
import com.wj.console.rpc.RpcResponse;
import com.wj.dubbo.service.cache.MyRedisCache;
import com.wj.dubbo.service.cache.MyRedisCacheManager;
import com.wj.dubbo.service.crawler.service.impl.CrawlSocialService;
import com.wj.dubbo.utils.HttpClient;
import com.wj.dubbo.utils.Md5;

/**   
 * 类名称：WelfareShopCallService
 * 类描述 ：福利商城接口调用服务类
 * 创建人: liuweidong  
 * 创建时间：2017-5-5 下午1:18:21  
 * 修改人：
 * 修改时间：
 * 修改备注：
 * 版本： V1.0
 */

@Service
public class WelfareShopCallService {
	private static final Logger log = LoggerFactory.getLogger(WelfareShopCallService.class);
	
	@Autowired
    private MyRedisCacheManager manager;
	
/*	public static final String SHOP_WID = "1068";
	public static final String SHOP_ACCESSTOKEN = "pzFFwCctGVRXWKf7gxdt3pSfua9eNT";
	public static final String SHOP_INTERFACEURL = "http://beta.open.limofang.cn";*/
	
	public static final String SHOP_WID = "1164";
	public static final String SHOP_ACCESSTOKEN = "bcakqJ2u5zuCwKbvG9dvzjmwe7gFXH";
	public static final String SHOP_INTERFACEURL = "http://open.fygift.com";
	
	//商品接口
	public static final String GETALLIDS = SHOP_INTERFACEURL + "/api/product/getAllIds.php";	//1.1获取所有商品ID
	public static final String GETPRODUCTIDSBYPAGE = SHOP_INTERFACEURL +"/api/product/getProductIdsByPage.php";	//1.2分页获取当前页商品ID, 每页数据100条
	public static final String PRODUCTDETIAL = SHOP_INTERFACEURL +"/api/product/detial.php";	//1.3获取单个商品详情
	public static final String STOCK = SHOP_INTERFACEURL +"/api/product/stock.php";	//1.4单个查询商品库存
	public static final String STOCKBATCH = SHOP_INTERFACEURL +"/api/product/stockBatch.php";	//1.5批量查询商品库存
	public static final String SALESTATUS = SHOP_INTERFACEURL +"/api/product/saleStatus.php";	//1.6查询商品可售状态
	public static final String GETPRICE = SHOP_INTERFACEURL +"/api/product/getPrice.php";	//1.7查询商品协议价
	public static final String BATCHSALESTATUS = SHOP_INTERFACEURL +"/api/product/batchSaleStatus.php";	//1.8批量查询商品可售状态
	public static final String BATCHGETPRICE = SHOP_INTERFACEURL +"/api/product/batchGetPrice.php";	//1.9批量查询商品协议价
	
	//订单接口
	public static final String SUBMIT = SHOP_INTERFACEURL +"/api/order/submit.php";	//2.1创建订单接口
	public static final String ORDERDETAIL = SHOP_INTERFACEURL +"/api/order/detail.php";	//2.2查询订单详情接口
	public static final String THIRDORDER = SHOP_INTERFACEURL +"/api/order/thirdOrder.php";	//2.3订单反查询接口, 用于确认订单是否创建成功
	public static final String ORDERTRACK = SHOP_INTERFACEURL +"/api/order/orderTrack.php";	//2.4订单物流信息接口-根据己方订单号获取
	public static final String SYSTEMORDERTRACK = SHOP_INTERFACEURL +"/api/order/systemOrderTrack.php";	//2.5订单物流信息接口-根据我方订单号获取
	
	//预存款接口
	public static final String REMAIN = SHOP_INTERFACEURL +"/api/finance/remain.php";	//3.1查询预存款余额
	
	//地址接口
	public static final String PROVINCE = SHOP_INTERFACEURL +"/api/area/province.php";	//4.1获取一级地址(省份)
	public static final String CITY = SHOP_INTERFACEURL +"/api/area/city.php";	//4.2获取二地址(城市)
	public static final String COUNTY = SHOP_INTERFACEURL +"/api/area/county.php";	//4.3获取三级地址(县/区)
	public static final String TOWN = SHOP_INTERFACEURL +"/api/area/town.php";	//4.4获取四级地址(镇/街道)
	
	//系统产品分类接口
	public static final String ROOTCATE = SHOP_INTERFACEURL +"/api/cate/rootCate.php";	//5.1获取一级产品分类
	public static final String CHILDS = SHOP_INTERFACEURL +"/api/cate/childs.php";	//5.2获取下级产品分类
	public static final String CATEDETIAL = SHOP_INTERFACEURL +"/api/cate/detial.php";	//5.3获取单个分类详情
	
	//售后服务接口
	public static final String GETRETURNADDRESS = SHOP_INTERFACEURL +"/api/afterSale/getReturnAddress.php";	//6.1获取商品退货地址信息
	public static final String GETSTATUS = SHOP_INTERFACEURL +"/api/afterSale/getStatus.php";	//6.2查询订单商品是否可以进行退换货操作
	public static final String RETURN = SHOP_INTERFACEURL +"/api/afterSale/return.php";	//6.3申请退货
	public static final String NIFFER = SHOP_INTERFACEURL +"/api/afterSale/niffer.php";	//6.4申请换货
	public static final String AFTERSALEDETAIL = SHOP_INTERFACEURL +"/api/afterSale/detail.php"; //6.5售后订单详情
	
	
	/**
	 * 获取所有商品详情(跑批)
	 */
	public Map<String,ProductDetail> getAllProducts() {
		Map<String,ProductDetail> productMap = null;
		//商品分类信息
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_CATE.toString());
		Map<String,Cate> cateMap  = (Map<String,Cate>) cache.get(CACHE_KEY.WS_CATE_MAP_TILE.toString(),Map.class);
		if(cateMap == null||cateMap.isEmpty()){
			this.getAllCate();
			cateMap  = (Map<String,Cate>) cache.get(CACHE_KEY.WS_CATE_MAP_TILE.toString(),Map.class);
		}
		//所有商品ID接口调用
		Map<String, String> params = new HashMap<String, String>();
		ResultMsg resultMsg = callInterface(GETALLIDS,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			List<Integer> allPidList = new ArrayList<Integer>();
			productMap = new HashMap<String,ProductDetail>();
			List<Map<String,Object>> dataList = (List<Map<String,Object>>)resultMsg.getResultData();
			for(Map<String,Object> dataMap:dataList){
				List<Integer> pidList = (List<Integer>)dataMap.get("pid");
				allPidList.addAll(pidList);
			}
			if(allPidList!=null&&allPidList.size()!=0){
				ResultMsg productResultMsg = null;
				Boolean productResponseStatus = null;
				for(Integer pid:allPidList){
					//获取单个商品详情接口调用
					productResultMsg = getProductResultMsg(String.valueOf(pid));
					productResponseStatus = productResultMsg.getResponseStatus();
					if(productResponseStatus){
						ProductDetail product = this.getProduct(productResultMsg);
						////////////2017/6/24  由于样式问题过滤掉云中鹤第三方产品(京东)
						if("jindong".equals(product.getType())){
							continue;
						}
						////////////
						this.disposeCate(product,cateMap);
						productMap.put(product.getProductId().toString(), product);
					}else{
						throw new BusinessException(productResultMsg.getErrorCode(), productResultMsg.getErrorMessage());
					}
				}
			}
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return productMap;
	}
	
	//设置商品的三级分类信息
	private void disposeCate(ProductDetail product, Map<String, Cate> cateMap) {
		String productCate = product.getProductCate().toString();
		Cate cate = cateMap.get(productCate);
		String parentId = null;
		if(cate!=null){
			switch (cate.getLevel().toString()) {
			//一级
			case "0":
				product.setRootCate(cate.getCode());
				break;
			//二级
			case "1":
				parentId = cate.getParentId();
				product.setRootCate(parentId);
				product.setTwoCate(cate.getCode());
				break;
			//三级
			case "2":
				parentId = cate.getParentId();//二级
				if(cateMap.get(parentId)==null){
					log.error("三级商品分类父ID:"+parentId+"  根据此父ID找不到相关分类信息");
					break;
				}
				product.setRootCate(cateMap.get(parentId).getParentId());
				product.setTwoCate(parentId);
				product.setThreeCate(cate.getCode());
				break;
			default:
				break;
			}
		}
	}

	private ResultMsg getProductResultMsg(String pid) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid",pid);
		ResultMsg resultMsg = callInterface(PRODUCTDETIAL,params);
		return resultMsg;
	}
	
	private ProductDetail getProduct(ResultMsg resultMsg) {
		Map<String, Object> resultData = (Map<String, Object>)resultMsg.getResultData();
		String productData = resultData.get("PRODUCT_DATA").toString();
		ProductDetail product = JSON.parseObject(productData,ProductDetail.class);
		
		String productDescription = (String)resultData.get("PRODUCT_DESCRIPTION");
		String imageData = resultData.get("PRODUCT_IMAGE").toString();
		List<Image> images = JSON.parseArray(imageData, Image.class);
		
		product.setDescription(productDescription);
		product.setImages(images);
		return product;
	}

	/**
	 * 单个查询商品库存
	 * @param pid 商品ID
	 * @param num 数量
	 * @param address 配送地址ID,格式：1_0_0 (分别代表1、2、3级地址)
	 */
	public Stock stock(String pid, String num, String address) {
		Stock stock = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid",pid);
		params.put("num",num);
		params.put("address",address);
		ResultMsg resultMsg = callInterface(STOCK,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			stock = JSON.parseObject(resultData,Stock.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return stock;
	}

	/**
	 * 批量查询商品库存
	 * @param pidNums 商品ID_数量， 多个使用逗号(,)拼接即可. 例如: 20169_1, 23908_2, 20167_3
	 * @param address 配送地址ID,格式：1_0_0 (分别代表1、2、3级地址)
	 */
	public List<Stock> stockBatch(String pidNums, String address) {
		List<Stock>  stocks= null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid_nums",pidNums);
		params.put("address",address);
		ResultMsg resultMsg = callInterface(STOCKBATCH,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			stocks= JSON.parseArray(resultData,Stock.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return stocks;
	}
	
	/**
	 * 查询商品可售状态
	 * @param pid 商品ID
	 */
	public CommodityStatus saleStatus(String pid) {
		CommodityStatus commodityStatus = null;		
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid",pid);
		ResultMsg resultMsg = callInterface(SALESTATUS,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		System.out.println(responseStatus);
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			commodityStatus= JSON.parseObject(resultData,CommodityStatus.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return commodityStatus;
	}

	/**
	 * 批量查询商品可售状态
	 * @param pids 商品ID,多个使用逗号(,)连接即可。例如: pid =20169,20178,23908
	 */
	public List<CommodityStatus> batchSaleStatus(String pids) {
		List<CommodityStatus> commodityStatus = null;
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("pids",pids);
		ResultMsg resultMsg = callInterface(BATCHSALESTATUS,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			commodityStatus= JSON.parseArray(resultData,CommodityStatus.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return commodityStatus;
	}

	/**
	 * 查询商品协议价
	 * @param pid 商品ID
	 */
	public Price getPrice(String pid) {
		Price price = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid",pid);
		ResultMsg resultMsg = callInterface(GETPRICE,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			price = JSON.parseObject(resultData,Price.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return price;
	}

	/**
	 * 批量查询商品协议价
	 * @param pids 商品ID,多个使用逗号(,)连接即可。例如: pid =20169,20178,23908
	 */
	public List<Price> batchGetPrice(String pids) {
		List<Price> prices = null;		
		Map<String, String> params = new HashMap<String, String>();
		params.put("pids",pids);
		ResultMsg resultMsg = callInterface(BATCHGETPRICE,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			prices = JSON.parseArray(resultData,Price.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return prices;
	}

	/**
	 * 提交订单
	 * @param createOrderParam 创建订单参数
	 */
	public CreateOrderResult submitOrder(CreateOrderParam createOrderParam) {
		CreateOrderResult createOrderResult = null;		
		Map<String, String> params = new HashMap<String, String>();
		params.put("thirdOrder",createOrderParam.getThirdOrder());
		params.put("pid_nums",createOrderParam.getPidNums());
		params.put("receiverName",createOrderParam.getReceiverName());
		params.put("province",createOrderParam.getProvince());
		params.put("city",createOrderParam.getCity());
		params.put("county",createOrderParam.getCounty());
		params.put("town",createOrderParam.getTown());
		params.put("address",createOrderParam.getAddress());
		params.put("mobile",createOrderParam.getMobile());
		params.put("email",createOrderParam.getEmail());
		params.put("remark",createOrderParam.getRemark());
		
		ResultMsg resultMsg = callInterface(SUBMIT,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			createOrderResult = JSON.parseObject(resultData,CreateOrderResult.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return createOrderResult;
	}

	/**
	 * 查询订单详情
	 * @param orderKey 礼魔方系统订单号
	 */
	public OrderDetail orderDetail(String orderKey) {
		OrderDetail orderDetail = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderKey",orderKey);
		ResultMsg resultMsg = callInterface(ORDERDETAIL,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString().replace("CHILD_ORDERS","child_orders");
			orderDetail= JSON.parseObject(resultData,OrderDetail.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return orderDetail;
	}

	/**
	 * 订单反查询, 用于确认订单是否创建成功
	 * @param thirdOrder 我方生成系统订单号
	 */
	public String orderSure(String thirdOrder) {
		String resultData = null;
		RpcResponse<String> response = new RpcResponse<String>();
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("thirdOrder",thirdOrder);
		ResultMsg resultMsg = callInterface(THIRDORDER,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			resultData = (String)resultMsg.getResultData();  //系统订单号
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return resultData;
	}

	/**
	 * 订单物流信息接口-根据我方订单号获取
	 * @param thirdOrder 我方生成系统订单号
	 */
	public LogisticsMsg orderTrack(String thirdOrder) {
		LogisticsMsg logisticsMsg = null;
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("thirdOrder",thirdOrder);
		ResultMsg resultMsg = callInterface(ORDERTRACK,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			logisticsMsg= JSON.parseObject(resultData,LogisticsMsg.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return logisticsMsg;
	}

	/**
	 * 订单物流信息接口-根据礼魔方订单号获取
	 * @param orderKey 礼魔方系统订单号
	 */
	public LogisticsMsg systemOrderTrack(String orderKey) {
		LogisticsMsg logisticsMsg = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderKey",orderKey);
		ResultMsg resultMsg = callInterface(SYSTEMORDERTRACK,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			logisticsMsg = JSON.parseObject(resultData,LogisticsMsg.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return logisticsMsg;
	}
	
	/**
	 * 查询预存款余额
	 * @return  预存款余额信息
	 */
	public Remain remain() {
		Remain remain = null;
		Map<String, String> params = new HashMap<String, String>();
		ResultMsg resultMsg = callInterface(REMAIN,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString().replace("REMAIN", "remain")
										.replace("CREDIT_TOTAL","creditTotal").replace("CREDIT_USED", "creditUsed");
			remain= JSON.parseObject(resultData,Remain.class);
			System.out.println(remain);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return remain;
	}
	
	/**
	 * 获取所有地址
	 * @return RpcResponse data 所有地址
	 */
	public Map<String,Address> getAllAddress() {
		List<Address> addressList = new ArrayList<Address>();
		Map<String,Address> provinceMap = null;	//省
		Map<String,Address> cityMap = null;	//市
		Map<String,Address> countyMap = null;	//区
		Map<String,Address> townMap = null;	//镇
		
		ResultMsg resultMsg = null;
		Boolean responseStatus = null;
		//省份
		resultMsg = getAddressResultMsg("province", null);
		responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			List<Address> provinceList = getAddressList(null, resultMsg);
			if(provinceList!=null&&provinceList.size()!=0){
				for(Address province:provinceList){
					//城市
					resultMsg = getAddressResultMsg("city", province.getCode());
					responseStatus = resultMsg.getResponseStatus();
					if(responseStatus){
						List<Address> cityList = getAddressList(province.getCode(), resultMsg);
						if(cityList!=null&&cityList.size()!=0){
							for(Address city:cityList){
								//区/县
								resultMsg = getAddressResultMsg("county", city.getCode());
								responseStatus = resultMsg.getResponseStatus();
								if(responseStatus){
									List<Address> countyList = getAddressList(city.getCode(), resultMsg);
									if(countyList!=null&&countyList.size()!=0){
										for(Address county:countyList){
											//镇/街道
											resultMsg = getAddressResultMsg("town", county.getCode());
											responseStatus = resultMsg.getResponseStatus();
											if(responseStatus){
												List<Address> townList = getAddressList(county.getCode(), resultMsg);
												if(townList!=null&&townList.size()!=0){
													addressList.addAll(townList);	//添加镇/街道
													//放入Map
													townMap = new HashMap<String,Address>();
													townMap = Maps.uniqueIndex(townList, new Function <Address,String> () {
												          public String apply(Address from) {
												            return from.getCode(); 
												    }});
													county.setAddressMap(townMap);
												}
											}else{
												throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
											}
										}
										addressList.addAll(countyList);	//添加区/县
										//放入Map
										countyMap = new HashMap<String,Address>();
										countyMap = Maps.uniqueIndex(countyList, new Function <Address,String> () {
									          public String apply(Address from) {
									            return from.getCode(); 
									    }});
										city.setAddressMap(countyMap);
									}
								}else{
									throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
								}
							}
							addressList.addAll(cityList);	//添加城市
							//放入Map
							cityMap = new HashMap<String,Address>();
							cityMap = Maps.uniqueIndex(cityList, new Function <Address,String> () {
						          public String apply(Address from) {
						            return from.getCode(); 
						    }});
							province.setAddressMap(cityMap);
						}
					}else{
						throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
					}
				}
				addressList.addAll(provinceList);	//添加省
				//放入Map
				provinceMap = new HashMap<String,Address>();
				provinceMap = Maps.uniqueIndex(provinceList, new Function <Address,String> () {
			          public String apply(Address from) {
			            return from.getCode(); 
			    }});
			}
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		//放入缓存
		Map<String,Address> map = new HashMap<String,Address>();
		map.putAll(provinceMap);
		//过滤钓鱼岛
		String diaoYuDaoCode = "";
		for(String addressCode:map.keySet()){
			 if("钓鱼岛".equals(map.get(addressCode).getName())){
				 diaoYuDaoCode = addressCode;
				 break;
			 }
		}
		if(!"".equals(diaoYuDaoCode)){
			map.remove(diaoYuDaoCode);
		}
		MyRedisCache cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_ADDRESS.toString());
		cache.put(CACHE_KEY.WS_ADDRESS_MAP_TREE.toString(), map);//树状结构 
		//平铺缓存内容不需要包含子区域内容，否则序列化时递归操作
		for(Address addr : addressList){
			addr.setAddressMap(null);
		}
		
		Map<String,Address> addressTileMap = Maps.uniqueIndex(addressList, new Function <Address,String> () {
			public String apply(Address from) {
				return from.getCode(); 
		    }});
		cache.put(CACHE_KEY.WS_ADDRESS_MAP_TILE.toString(), addressTileMap);//平铺结构
		
		return provinceMap;
	}

	int count = 0;
	private ResultMsg getAddressResultMsg(String addressType, String code) {
		System.out.println(++count);
		Map<String, String> params = new HashMap<String, String>();
		String url = ""; 
		switch (addressType) {
		case "province":
			url = PROVINCE;
			break;
		case "city":
			url = CITY;
			params.put("province", code); 
			break;
		case "county":
			url = COUNTY;
			params.put("city", code); 
			break;
		case "town":
			url = TOWN;
			params.put("county", code); 
			break;
		default:
			break;
		}
		ResultMsg resultMsg = callInterface(url,params);
		return resultMsg;
	}
	
	private List<Address> getAddressList(String code, ResultMsg resultMsg) {
		String addressStr = resultMsg.getResultData().toString();
		List<Address> addressList = JSON.parseArray(addressStr, Address.class);
		for(Address address:addressList){
			address.setParentCode(code);
		}
		return addressList;
	}

	/**
	 * 获取产品分类
	 * @param parentCate 分类父ID
	 */
	public List<Cate> getCate(String parentCate) {
		List<Cate> cateList = null;
		Map<String, String> params = new HashMap<String, String>();
		String url = "";
		//获取下级产品分类
		if(StringUtils.isNotEmpty(parentCate)){
			url = CHILDS;
			params.put("parentCate",parentCate);
		//获取一级产品分类
		}else{
			url = ROOTCATE;
		}
		ResultMsg resultMsg = callInterface(url,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String cateStr = resultMsg.getResultData().toString();
			cateList = JSON.parseArray(cateStr, Cate.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return cateList;
	}
	
	/**
	 * 获取所有产品分类
	 * @param type 1:树状结构数据  2:平铺状数据
	 */
	public void getAllCate() {
		List<Cate> cateList = new ArrayList<Cate>();
		Map<String,Cate> rootMap = null;	//一级分类
		Map<String,Cate> twoMap = null;	//二级分类
		Map<String,Cate> threeMap = null;	//三级分类
		
		ResultMsg resultMsg = null;
		Boolean responseStatus = null;
		String cateStr = null;
		
		Map<String, String> params = new HashMap<String, String>();
		
		resultMsg = callInterface(ROOTCATE,params);
		responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			cateStr = resultMsg.getResultData().toString();
			//一级分类
			List<Cate> rootCateList = JSON.parseArray(cateStr, Cate.class);
			if(rootCateList!=null&&rootCateList.size()!=0){
				for(Cate rootCate:rootCateList){
					if("工艺品".equals(rootCate.getName())){
						rootCate.setName("其他商品");
					}
					params = new HashMap<String, String>();
					params.put("parentCate", rootCate.getCode());
					resultMsg = callInterface(CHILDS,params);
					responseStatus = resultMsg.getResponseStatus();
					if(responseStatus){
						 cateStr = resultMsg.getResultData().toString();
						 //二级分类
						 List<Cate> twoCateList = JSON.parseArray(cateStr, Cate.class);
						 if(twoCateList!=null&&twoCateList.size()!=0){
							for(Cate twoCate:twoCateList){
								params = new HashMap<String, String>();
								params.put("parentCate", twoCate.getCode());
								resultMsg = callInterface(CHILDS,params);
								responseStatus = resultMsg.getResponseStatus();
								if(responseStatus){
									 cateStr = resultMsg.getResultData().toString();
									 //三级分类
									 List<Cate> threeCateList = JSON.parseArray(cateStr, Cate.class);
									 if(threeCateList!=null&&threeCateList.size()!=0){
										 cateList.addAll(threeCateList);	//添加三级分类
										//放入Map
										threeMap = new HashMap<String,Cate>();
										threeMap = Maps.uniqueIndex(threeCateList, new Function <Cate,String> () {
									          public String apply(Cate from) {
									            return from.getCode(); 
									    }});
										twoCate.setCateMap(threeMap);
									 }
								}else{
									throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
								}
							}
							cateList.addAll(twoCateList);//添加二级分类
							//放入Map
							twoMap = new HashMap<String,Cate>();
							twoMap = Maps.uniqueIndex(twoCateList, new Function <Cate,String> () {
						          public String apply(Cate from) {
						            return from.getCode(); 
						    }});
							rootCate.setCateMap(twoMap);
						 }
					}else{
						throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
					}
				}
				cateList.addAll(rootCateList);//添加一级分类
				//放入Map
				rootMap = new HashMap<String,Cate>();
				rootMap = Maps.uniqueIndex(rootCateList, new Function <Cate,String> () {
			          public String apply(Cate from) {
			            return from.getCode(); 
			    }});
			}
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		//放入缓存
		MyRedisCache  cache = (MyRedisCache)manager.getCache(CACHE_KEY.WS_CATE.toString());
		cache.put(CACHE_KEY.WS_CATE_MAP_TREE.toString(), rootMap);//树状结构
		
		//平铺缓存内容不需要包含子区域内容，否则序列化时递归操作
		for(Cate cate : cateList){
			cate.setCateMap(null);
		}
		Map<String,Cate> cateTileMap = Maps.uniqueIndex(cateList, new Function <Cate,String> () {
				public String apply(Cate from) {
					return from.getCode(); 
			    }});
		cache.put(CACHE_KEY.WS_CATE_MAP_TILE.toString(), cateTileMap);//平铺结构
	}

	/**
	 * 获取商品退货地址信息
	 * @param pid 商品ID 
	 */
	public SalesReturnMsg getReturnAddress(String pid) {
		SalesReturnMsg salesReturnMsg = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("pid", pid); 	//商品ID
		ResultMsg resultMsg = callInterface(GETRETURNADDRESS,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String salesReturnMsgStr = resultMsg.getResultData().toString();
			salesReturnMsg = JSON.parseObject(salesReturnMsgStr, SalesReturnMsg.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return salesReturnMsg;
	}

	/**
	 * 查询订单商品是否可以进行退换货操作
	 * @param orderKey 礼魔方系统订单号
	 * @param productIds 商品ID,如果有多个使用逗号(,)拼接, 例如: 232391,348273,58723
	 */
	public List<CommodityStatus>  getStatus(String orderKey, String productIds) {
		List<CommodityStatus> commodityStatus = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderKey",orderKey);
		params.put("productIds",productIds);
		ResultMsg resultMsg = callInterface(GETSTATUS,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String resultData = resultMsg.getResultData().toString();
			commodityStatus = JSON.parseArray(resultData,CommodityStatus.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return commodityStatus;
	}

	/**
	 * 退/换货
	 * @param salesReturnApplyParam 退/换货 参数
	 * @param dealType 交易类型(退货：return  换货：niffer)
	 */
	public SalesReturnOrNifferApplyResult salesReturnOrNiffer(
			SalesReturnOrNifferApplyParam param, String dealType) {
		SalesReturnOrNifferApplyResult result = null;
		String url = "";
		switch (dealType) {
		case "return":
			url = RETURN;
			break;
		case "niffer":
			url = NIFFER;
			break;
		default:
			break;
		}
		Map<String, String> params=new HashMap<String, String>();
		params.put("orderKey",param.getOrderKey());
		params.put("pid_nums",param.getPidNums());
		params.put("shipmentCompany",param.getShipmentCompany());
		params.put("shipmentOrder",param.getShipmentOrder());
		params.put("reason",param.getReason());
		params.put("userMobile",param.getUserMobile());
		params.put("userRemark",param.getUserRemark());
		
		ResultMsg resultMsg = callInterface(url,params);
		Boolean responseStatus = resultMsg.getResponseStatus(); 
		if(responseStatus){
			String salesReturnMsgStr = resultMsg.getResultData().toString().replace("RETURN_ENTRY", "return_entry");//getSalesReturnStr().replace("RETURN_ENTRY", "return_entry");
			result = JSON.parseObject(salesReturnMsgStr, SalesReturnOrNifferApplyResult.class);
			result.setResultJson(salesReturnMsgStr);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return result;
	}
	
	/**
	 * 售后订单详情
	 * @param orderKey 礼魔方系统订单号
	 * @return RpcResponse data 售后订单详情
	 */
	public AfterSaleDetail afterSaleDetail(String orderKey) {
		AfterSaleDetail afterSaleDetail = null;
		Map<String, String> params = new HashMap<String, String>();
		params.put("orderKey", orderKey); 	//礼魔方系统订单号
		ResultMsg resultMsg = callInterface(AFTERSALEDETAIL,params);
		Boolean responseStatus = resultMsg.getResponseStatus();
		if(responseStatus){
			String afterSaleDetailStr = resultMsg.getResultData().toString();
			afterSaleDetail= JSON.parseObject(afterSaleDetailStr, AfterSaleDetail.class);
		}else{
			throw new BusinessException(resultMsg.getErrorCode(), resultMsg.getErrorMessage());
		}
		return afterSaleDetail;
	}
	
	
	/**
	 * 
	 * @param url 调用URL
	 * @param params 参数
	 * @param ResultMsg 调用返回结果对象
	 */
	private ResultMsg callInterface(String url,Map<String, String> params) {
		//结果集
		Map<String, Object> resultMap = null;
		ResultMsg resultMsg = null;
		//组装公共参数
		String timestamp = Long.toString(System.currentTimeMillis());
		params.put("wid", SHOP_WID);
		params.put("token", getToken(SHOP_WID,SHOP_ACCESSTOKEN,timestamp));
		params.put("timestamp",timestamp);
		//接口调用
		String result = HttpClient.post(url, params);
		log.info("福利商城云中鹤接口调用：{url:"+url+"    params:"+params+"    result:"+result);
		//封装返回结果
		if(StringUtils.isNotBlank(result)){
			resultMap = JSON.parseObject(result); 
			Boolean responseStatus = Boolean.valueOf((String)resultMap.get("RESPONSE_STATUS"));
			String errorCode = (String)resultMap.get("ERROR_CODE");
			String errorMessage = (String)resultMap.get("ERROR_MESSAGE");
			resultMsg = new ResultMsg();
			resultMsg.setResponseStatus(responseStatus);
			resultMsg.setErrorCode(errorCode);
			resultMsg.setErrorMessage(errorMessage);
			resultMsg.setResultData(resultMap.get("RESULT_DATA"));
		}
		return resultMsg;
	}
	
	private static String getToken(String wid,String accessToken,String tm){
		String sk=String.format("%s%s%s", wid,accessToken,tm);
		return Md5.encrypt(sk).toUpperCase();
	}
}
